package itsm.isperp.module.service.bpm.act;

import itsm.isperp.module.repository.bpm.act.BpmActMapper;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

/**
 * BPM对引擎操作的服务
 * 
 * 
 * @author lizx
 * @date 2013-7-1
 * 
 */
@Service
public class BpmActService {

	@Autowired
	BpmActMapper bpmActMapper;

	/**
	 * 根据流程部署id获取流程定义的xml文本（UTF-8编码）
	 * 
	 * @param deploymentId
	 *            流程部署id
	 * @return 流程定义的xml文本（UTF-8编码）
	 * @throws UnsupportedEncodingException
	 *             如果获取的不是字符串结果
	 */
	public String getProcessDefinitionXmlByDeployId(String deploymentId)
			throws UnsupportedEncodingException {
		Object o = this.bpmActMapper
				.findProcessDefinitionXmlByDeployId(deploymentId);
		byte[] bs = null;
		if (o instanceof oracle.sql.BLOB) {

			oracle.sql.BLOB blob = (oracle.sql.BLOB) o;
			InputStream ops = null;
			try {
				ops = blob.getBinaryStream();
				bs = FileCopyUtils.copyToByteArray(ops);
			} catch (Exception e) {
				throw new RuntimeException(
						"get process definition xml bytes error", e);
			} finally {
				try {
					if (ops != null) {
						ops.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		} else if (o instanceof String) {
			return o.toString();
		} else {
			bs = (byte[]) o;
		}
		return new String(bs, "UTF-8");

	}

	/**
	 * 更新activiti中大数据类型变量的值
	 * 
	 * @param id
	 *            变量表的id
	 * @param bytes
	 *            二进制集合（UTF-8编码）
	 */
	public void updateActGeByteArray(String id, byte[] bytes) {
		this.bpmActMapper.updateActGeByteArray(id, bytes);
	}

	/**
	 * 跟新流程定义的xml
	 * 
	 * @param deployId
	 *            部署id
	 * @param defXml
	 *            流程定义xml文本（UTF-8编码）
	 */
	public void updateDefXml(String deployId, byte[] defXml) {
		this.bpmActMapper.updateDefXml(deployId, defXml);
	}

}
